package com.sinven.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.sinven.pojo.Article;
import com.sinven.pojo.Picture;
import com.sinven.pojo.User;
import com.sinven.service.ArticleService;
import com.sinven.service.PictureService;

/**
 * 添加文章
 * 
 * @author 李志伟
 *
 */
@Controller

public class AddArticleController {

	@Autowired
	ArticleService articleService;
	@Autowired
	PictureService pictureService;

	@RequestMapping({ "AddArticle" })
	public String article() {
	
		return "pages/AddArticle";
	}
	
	@RequestMapping("upload")
	@ResponseBody
	public Picture addPicture(@RequestParam("upload")MultipartFile file, HttpServletRequest request) throws Exception {
		System.out.println(file.getOriginalFilename());
		// 保存

		// 得到后缀
		String oldFileName = file.getOriginalFilename();
		String suffix = oldFileName.substring(oldFileName.lastIndexOf('.'));
		// 产生新文件名
		String newFileName = UUID.randomUUID().toString() + suffix;
		// 目标文件
		File dest = new File("E:/project/upload/", newFileName);
		// 转存
		try {
			file.transferTo(dest);

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
//你们图片是分开存  这里就要存储到数据库
		Picture picture = new Picture();
		picture.setP_content("upload/" + newFileName);
		Picture pic = pictureService.addPicture(picture);
		System.out.println(pic);
		return pic;
		// 返回图片的访问URL

	}

	/**
	 * 添加文章的controller
	 * 
	 * @param article
	 * @param session
	 * @param p_content
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/article")
	@ResponseBody
	public boolean addArticle(Article article, HttpSession session, String p_content) throws Exception {
		User user = (User)session.getAttribute("user");
		
		article.setA_authorId(user); 
		
		boolean res = articleService.AddArticle(article);
		if(res==true) {
			return res;
		}
		return res;

	}
	/**
	 * 修改文章
	 * @param model
	 * @param a_id
	 * @return
	 * @throws Exception
	 */
	@GetMapping({ "UpdataArticle" })
	public String UpdataArticle(Model model,int a_id) throws Exception {
		Article selectArticleContent = articleService.SelectArticleContent(a_id);
		model.addAttribute("selectArticleContent", selectArticleContent);
		return "pages/update_article";
		

	}
	
	

	
}
